﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ColorComboBox.h"
#include "./DisplayWidget/ImageView.h"
#include "./DisplayWidget/DisplayWidget.h"
#include "./DisplayWidget/element.h"
#include "./qtOpenCV/convert.h"
#include "opencv2/highgui.hpp"
#include <QLabel>
#include <QDebug>
#include <QPushButton>
#include <QSpinBox>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QSettings>
#include <QCheckBox>
#include <QStandardPaths>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_lens(LEN0),
    m_pTisCamera(nullptr),
    m_timerXYZPos(nullptr),
    m_isMeasure(false)
{
    ui->setupUi(this);
    setWindowTitle(u8"北京经海科技有限公司");
    m_centerWidget = new DisplayWidget(ImageView::RGB24, this);
    m_centerWidget->setDrawType(Element::NONE);
    m_scrollArea = new QScrollArea(this);
    setCentralWidget(m_scrollArea);
    m_scrollArea->setWidget(m_centerWidget);
    m_scrollArea->setAlignment(Qt::AlignCenter);

    m_cameraImage = new CameraImage_RGB24(this);
    connect(m_cameraImage, SIGNAL(imageChanged(QImage)), m_centerWidget, SLOT(setRGB24Image(QImage)));

    QString path = configFilePath();
    QSettings settings( path + "/JHPhoto.ini", QSettings::IniFormat, this );
    m_lensCompensation.loadSettings(settings);
    qInfo() << path;

    setupToolBar(settings);

#ifdef TIS_CAMERA
    setupTisCamera();
#endif //TIS_CAMERA
    setupScale(settings);

    connect(ui->actionOpen, SIGNAL(triggered(bool)), this, SLOT(loadImage()));
    connect(ui->actionSaveWithMark, SIGNAL(triggered()), this, SLOT(saveImageWithMark()));
    connect(ui->actionSaveWithoutMark, SIGNAL(triggered()), this, SLOT(saveImageWithoutMark()));

    m_pStageControlPad = new StageControlDockWidget(this);
    addDockWidget(Qt::RightDockWidgetArea, m_pStageControlPad);
    m_pStageControlPad->enableGoHome(false);
    //m_pStageControlPad->enableXYControl(false);
    connect(ui->actionGoHome, SIGNAL(triggered(bool)), this, SLOT(showGoHomeDialg()));

    //setupJoyStick(settings);
    setupDMCB140M(settings);
    //QThread::sleep(1);
    setupStageControl(settings);

    setupNosepiece(settings);

    showGoHomeDialg();
    if(m_timerXYZPos)m_timerXYZPos->start();
    setWindowState(Qt::WindowMaximized);
}

void MainWindow::setupNosepiece(QSettings &settings)
{
    m_nosepiece = new NosepieceOlympusREMCB(this);
    m_nosepiece->loadSettings(settings);
    m_nosepiece->login();
    connect(m_toolbarNosepiece, SIGNAL(changeLens(int,int)), m_nosepiece,SLOT(setLens(int,int)));
    connect(m_toolbarNosepiece, SIGNAL(changeLens(int, int)), this, SLOT(changeRuler(int, int )));
    connect(m_toolbarNosepiece, SIGNAL(changeLens(int, int)), this, SLOT(lensWDAdjust(int,int)));
}



void MainWindow::showGoHomeDialg()
{
    if(QMessageBox::question(NULL, u8"询问", u8"是否回零？") == QMessageBox::Yes)
    {
        QDialog dlg;
        connect(m_pStageControl, SIGNAL(GoHomeFinish()), &dlg, SLOT(close()));
        m_pStageControl->goHome();
        dlg.setWindowTitle(u8"提示");
        dlg.setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowMaximizeButtonHint);
        QHBoxLayout layout;
        dlg.setLayout(&layout);
        QLabel label;
        label.setText(u8"正在回零,请等待回零完成后再继续操作！");
        layout.addWidget(&label);
        dlg.exec();
    }
}



void MainWindow::showBatchDialog()
{
}

void MainWindow::setupStageControl(QSettings &settings)
{
    m_pStageControl = new StageControl(m_b140card, this);
    m_pStageControl->loadSettings(settings);

    connect(m_pStageControlPad, SIGNAL(moveLeft(double)), m_pStageControl, SLOT(moveLeft(double)));
    connect(m_pStageControlPad, SIGNAL(moveRight(double)), m_pStageControl, SLOT(moveRight(double)));
    connect(m_pStageControlPad, SIGNAL(moveLeftStop()), m_pStageControl, SLOT(stopX()));
    connect(m_pStageControlPad, SIGNAL(moveRightStop()), m_pStageControl, SLOT(stopX()));

    connect(m_pStageControlPad, SIGNAL(moveForward(double)), m_pStageControl, SLOT(moveForward(double)));
    connect(m_pStageControlPad, SIGNAL(moveBackward(double)), m_pStageControl, SLOT(moveBackward(double)));
    connect(m_pStageControlPad, SIGNAL(moveForwardStop()), m_pStageControl, SLOT(stopY()));
    connect(m_pStageControlPad, SIGNAL(moveBackwardStop()), m_pStageControl, SLOT(stopY()));

    connect(m_pStageControlPad, SIGNAL(stopXY()), m_pStageControl, SLOT(stop()));

    connect(m_pStageControlPad, SIGNAL(moveUp(double)), m_pStageControl, SLOT(moveUp(double)));
    connect(m_pStageControlPad, SIGNAL(moveDown(double)), m_pStageControl, SLOT(moveDown(double)));
    connect(m_pStageControlPad, SIGNAL(moveUpStop()), m_pStageControl, SLOT(stopZ()));
    connect(m_pStageControlPad, SIGNAL(moveDownStop()), m_pStageControl, SLOT(stopZ()));

    connect(m_pStageControlPad, SIGNAL(stopZ()), m_pStageControl, SLOT(stop()));

    connect(m_pStageControlPad, SIGNAL(changeZSpeed(double)), m_pStageControl, SLOT(setZSpeed(double)));
    connect(m_pStageControlPad, SIGNAL(changeXYSpeed(double)), m_pStageControl, SLOT(setXSpeed(double)));
    connect(m_pStageControlPad, SIGNAL(changeXYSpeed(double)), m_pStageControl, SLOT(setYSpeed(double)));

    m_pStageControl->setXSpeed(1);
    m_pStageControl->setYSpeed(1);
    m_pStageControl->setZSpeed(0.3);


    connect(m_pStageControlPad, SIGNAL(goHomeX()), m_pStageControl, SLOT(goHomeX()));
    connect(m_pStageControlPad, SIGNAL(goHomeY()), m_pStageControl, SLOT(goHomeY()));
    connect(m_pStageControlPad, SIGNAL(goHomeZ()), m_pStageControl, SLOT(goHomeZ()));
    connect(m_pStageControlPad, SIGNAL(goHome()), m_pStageControl, SLOT(goHome()));

    //connect(m_centerWidget, SIGNAL(mousePosition(QPoint &)), this, SLOT(moveToRel(QPoint &)));
    m_timerXYZPos = new QTimer(this);
    m_timerXYZPos->setInterval(100);
    connect(m_timerXYZPos, SIGNAL(timeout()), this, SLOT(updatePos()));
    connect(m_timerXYZPos, SIGNAL(timeout()), this, SLOT(updateIO()));

}

void MainWindow::updatePos()
{
    m_pStageControl->updatePos(m_theoryPos_mm, m_encodePos_mm);
    m_pStageControlPad->setPosition(m_encodePos_mm[0], m_encodePos_mm[1], m_encodePos_mm[2]);
    //m_pStageControlPad->setPosition(m_theoryPos_mm[0], m_theoryPos_mm[1], m_theoryPos_mm[2]);
//    if(m_nozzleDockWidget)
//    {
//        m_nozzleDockWidget->setPosition(m_encodePos_mm[0], m_encodePos_mm[1]);
//    }
}

void MainWindow::updateIO()
{
    m_pStageControl->updateInputIO(m_io);
    if(m_io[0] == 0 && m_isMeasure)
    {
        emit autoPanelMeasure();
    }
}

void MainWindow::setupDMCB140M(QSettings &settings)
{
    m_b140card = new DMC_B140_M(this);
    QString ip = settings.value("B140M/IPAdress", "192.168.2.140").toString();
    qDebug() << "B140M/IPAdress: " << ip;
    m_b140card->connectViaEthernet(ip, 23);
}

void MainWindow::setupJoyStick(QSettings &settings)
{
    Q_UNUSED(settings);
    m_pJoyStick = new JoyStick2D(this);

    connect(m_pJoyStick, SIGNAL(Joy_MoveForward()), m_pStageControlPad, SIGNAL(joystick_moveForward()));
    connect(m_pJoyStick, SIGNAL(Joy_MoveForwardStop()), m_pStageControlPad, SIGNAL(moveForwardStop()));
    connect(m_pJoyStick, SIGNAL(Joy_MoveBackward()), m_pStageControlPad, SIGNAL(joystick_moveBackward()));
    connect(m_pJoyStick, SIGNAL(Joy_MoveBackwardStop()), m_pStageControlPad, SIGNAL(moveBackwardStop()));
    connect(m_pJoyStick, SIGNAL(Joy_MoveLeft()), m_pStageControlPad, SIGNAL(joystick_moveLeft()));
    connect(m_pJoyStick, SIGNAL(Joy_MoveLeftStop()), m_pStageControlPad, SIGNAL(moveLeftStop()));
    connect(m_pJoyStick, SIGNAL(Joy_MoveRight()), m_pStageControlPad, SIGNAL(joystick_moveRight()));
    connect(m_pJoyStick, SIGNAL(Joy_MoveRightStop()), m_pStageControlPad, SIGNAL(moveRightStop()));

    connect(m_pJoyStick, SIGNAL(Joy_Button8Pressed()), m_pStageControlPad, SLOT(zSpeedUp()));
    connect(m_pJoyStick, SIGNAL(Joy_Button4Pressed()), m_pStageControlPad, SLOT(zSpeedDown()));

    connect(m_pJoyStick, SIGNAL(Joy_Button7Pressed()), m_pStageControlPad, SIGNAL(joystick_moveUp()));
    connect(m_pJoyStick, SIGNAL(Joy_Button7Released()), m_pStageControlPad, SIGNAL(moveUpStop()));
    connect(m_pJoyStick, SIGNAL(Joy_Button3Pressed()), m_pStageControlPad, SIGNAL(joystick_moveDown()));
    connect(m_pJoyStick, SIGNAL(Joy_Button3Released()), m_pStageControlPad, SIGNAL(moveDownStop()));

    m_pJoyStick->listen();
}

QString MainWindow::configFilePath()
{
    QString path = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
    QDir dir;
    dir.mkpath(path);
    return path;
}

void MainWindow::lensWDAdjust(int oldLens, int newLens)
{
//    double x = m_lensCompensation.xCompensate(oldLens, newLens);
//    double y = m_lensCompensation.yCompensate(oldLens, newLens);
//    double z = m_lensCompensation.workingDistanceCompensate(oldLens, newLens);
//    m_stageControl->xyMoveToRelativePos(x, y, 1.0);
//    m_stageControl->zMoveToRelativePos(z, 1.0);
    //m_stageControl->moveToRelativePos(x, y, z, 2.0);
}

void MainWindow::changeRuler(int old, int len)
{
    Q_UNUSED(old);
    m_lens = len;
    m_centerWidget->setScale(m_scale[m_lens]);
}

QImage MainWindow::getImage()
{
    return m_cameraImage->getImage();
}

void MainWindow::setImage(QImage iamge)
{
    setCamera(false);
    Sleep(500);
    m_cameraImage->setImage(iamge);
}

void MainWindow::getEncodePosition(double encodePos_mm[])
{
    encodePos_mm[0] = m_encodePos_mm[0];
    encodePos_mm[1] = m_encodePos_mm[1];
    encodePos_mm[2] = m_encodePos_mm[2];
    encodePos_mm[3] = m_encodePos_mm[3];
}

void MainWindow::getTheoryPosition(double theoryPos_mm[])
{
    theoryPos_mm[0] = m_theoryPos_mm[0];
    theoryPos_mm[1] = m_theoryPos_mm[1];
    theoryPos_mm[2] = m_theoryPos_mm[2];
    theoryPos_mm[3] = m_theoryPos_mm[3];
}

double MainWindow::getScale()
{
    return m_scale[m_lens];
}

int MainWindow::getLens()
{
    return m_lens;
}

void MainWindow::setLens(int lens)
{
    m_nosepiece->setLens(lens);
    m_toolbarNosepiece->setLens(lens);
    changeRuler(0, lens);
}



bool MainWindow::setExpoureTime(int value)
{
    qDebug() << "setExpoureTime:" << value;
    return m_pTisCamera->setExpoureTime(value);
}

int MainWindow::getExpoureTime()
{
    return m_pTisCamera->expoureTime();
}

void MainWindow::moveToRelativePos(double x_mm, double y_mm, double z_mm, double speed)
{
    m_pStageControl->moveToRelativePos(x_mm, y_mm, z_mm, speed);
}

void MainWindow::calibrate()
{
    bool ok;
    double len = m_centerWidget->getLength(ok);
    if(!ok)
    {
        QMessageBox::information(this, QStringLiteral("Error"), QStringLiteral("Draw a line first!") );
        return ;
    }
    QString pw = QInputDialog::getText(this, "password", QStringLiteral("Password"), QLineEdit::Password, "", &ok );
    if(!ok || pw != "B3")
    {
        QMessageBox::information(this, QStringLiteral("Error"), QStringLiteral("Password is wrong!") );
        return ;
    }
    double real_len = QInputDialog::getDouble ( this, QStringLiteral("Calibrate"), QStringLiteral("Length(um)"), 1, 0.1, 10000, 1, &ok );
    if(ok)
    {
        m_scale[m_lens] = real_len / len;
        m_centerWidget->setScale(m_scale[m_lens]);
        QString path = configFilePath();
        QSettings settings( path + "/JHPhoto.ini", QSettings::IniFormat, this );
        switch(m_lens)
        {
        case LEN0:
            settings.setValue("Scale/LENS0", m_scale[m_lens]);
            break;
        case LEN1:
            settings.setValue("Scale/LENS1", m_scale[m_lens]);
            break;
        case LEN2:
            settings.setValue("Scale/LENS2", m_scale[m_lens]);
            break;
        case LEN3:
            settings.setValue("Scale/LENS3", m_scale[m_lens]);
            break;
        case LEN4:
            settings.setValue("Scale/LENS4", m_scale[m_lens]);
            break;
        case LEN5:
            settings.setValue("Scale/LENS5", m_scale[m_lens]);
            break;
        }
    }
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if( event->modifiers() & Qt::ControlModifier && event->key() == Qt::Key_F10)
    {
        calibrate();
    }
    if( event->modifiers() & Qt::ControlModifier && event->key() == Qt::Key_F11)
    {
        bool ok;
        QString pw = QInputDialog::getText(this, "password", QStringLiteral("Password"), QLineEdit::Password, "", &ok );
        if(!ok || pw != "B3")
        {
            QMessageBox::information(this, QStringLiteral("Error"), QStringLiteral("Password is wrong!") );
        }
        else
        {
            m_pStageControl->LECalibrator_show();
        }
    }
    QMainWindow::keyPressEvent(event);
}

void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
    if(event->button() == Qt::RightButton)
    {
        int pos_x = event->pos().x() - m_scrollArea->x() - m_centerWidget->x();
        int pos_y = event->pos().y() - m_scrollArea->y() - m_centerWidget->y();
        if(pos_x <= 0 || pos_x >= m_centerWidget->width() || pos_y <= 0 || pos_y >= m_centerWidget->height()) return;

        double move_x = (pos_x - m_centerWidget->width() / 2) * m_scale[m_lens] / m_toolbarZoom->getZoom();
        double move_y = (pos_y - m_centerWidget->height() / 2) * m_scale[m_lens] / m_toolbarZoom->getZoom();

        m_pStageControl->moveToRelativePos(move_x / 1000, move_y / 1000, 0);
    }
    QMainWindow::mouseDoubleClickEvent(event);
}

void MainWindow::setupScale(QSettings &settings)
{
    m_lens = settings.value("Nosepiece/LENS", 0).toInt();

    qDebug() << "m_lens = " << m_lens;
    m_scale[LEN0] = settings.value("Scale/LENS0", 200).toDouble();
    m_scale[LEN1] = settings.value("Scale/LENS1", 100).toDouble();
    m_scale[LEN2] = settings.value("Scale/LENS2", 50).toDouble();
    m_scale[LEN3] = settings.value("Scale/LENS3", 25).toDouble();
    m_scale[LEN4] = settings.value("Scale/LENS4", 10).toDouble();
    m_scale[LEN5] = settings.value("Scale/LENS5", 5).toDouble();

    m_centerWidget->setScale(m_scale[m_lens]);
    m_toolbarNosepiece->setLens(-1, m_lens);
}

void MainWindow::setupToolBar(QSettings &settings)
{
    m_toolbarMeasure = new ToolBarMeasure("ToolBarMeasure", this);
    m_toolbarMeasure->attach(m_centerWidget);
    addToolBar(Qt::TopToolBarArea, m_toolbarMeasure);

    m_toolbarZoom = new ToolBarZoom("ToolBarZoom", this);
    m_toolbarZoom->attach(m_centerWidget);
    addToolBar(Qt::TopToolBarArea, m_toolbarZoom);

    m_toolbarProperty = new ToolBarProperty("ToolbarProperty", this);
    m_toolbarProperty->attach(m_centerWidget);
    addToolBar(Qt::TopToolBarArea, m_toolbarProperty);
    addToolBarBreak();

    m_toolbarCamera = new ToolBarCamera("ToolBarCamera", this);
    m_toolbarCamera->attach(m_cameraImage, true);

    addToolBar(Qt::LeftToolBarArea, m_toolbarCamera);
    m_toolbarCamera->loadSettings(settings);
    m_toolbarCamera->enableFlip(false);
    //m_toolbarCamera->hideBayerSettings(true);

    //ui->toolBarMark->addSeparator();
//    ui->toolBarMarkSet->addAction(ui->actionCalibrate);
//    ui->toolBarMarkSet->setWindowTitle("Calibration Toolbar");
//    connect(ui->actionCalibrate, SIGNAL(triggered(bool)), this, SLOT(calibrate()));

    m_toolbarNosepiece = new ToolBarNosepiece;
    addToolBar(Qt::LeftToolBarArea, m_toolbarNosepiece);
}

void MainWindow::setCamera(bool on)
{
    if(m_pTisCamera->isValid())
    {
        if(on)
        {
            if(m_pTisCamera->startLive(false))
            {
                m_toolbarCamera->setStartCamera();
            }
        }
        else
        {
            m_pTisCamera->suspendLive();
            m_toolbarCamera->defaultCameraOpened();
        }
    }
}

#ifdef TIS_CAMERA
void MainWindow::setupTisCamera()
{
    m_pTisCamera = new TisCamera(this);

    connect(m_toolbarCamera, SIGNAL(selectCamera()), this, SLOT(selectTisCamera()));
    connect(m_toolbarCamera, SIGNAL(defaultCamera()), this, SLOT(defaultTisCamera()));
    connect(m_toolbarCamera, SIGNAL(closeCamera()), this, SLOT(closeTisCamera()));
    connect(m_toolbarCamera, SIGNAL(startCamera()), this, SLOT(startTisCamera()));
    connect(m_toolbarCamera, SIGNAL(suspendCamera()), this, SLOT(suspendTisCamera()));
    connect(m_toolbarCamera, SIGNAL(setupCamera()), this, SLOT(adjustTisCamera()));

    connect(m_pTisCamera, SIGNAL(Mono8ImageChanged(const uint8_t*,QSize)), m_cameraImage, SLOT(setBayerImage(const uint8_t*,QSize)));
   //connect(m_tisCamera, SIGNAL(Mono8ImageChanged(const uint8_t*,QSize)), m_cameraImage_RGB32, SLOT(setMono8Image(const uint8_t*,QSize)));
    connect(m_pTisCamera, SIGNAL(RGB24ImageChanged(const uint8_t*,QSize)), m_cameraImage, SLOT(setRGB24Image(const uint8_t*,QSize)));
    connect(m_pTisCamera, SIGNAL(RGB32ImageChanged(const uint8_t*,QSize)), m_cameraImage, SLOT(setRGB32Image(const uint8_t*,QSize)));
    connect(m_pTisCamera, SIGNAL(deviceLost()), m_toolbarCamera, SLOT(cameraLost()));

    connect(m_pTisCamera, SIGNAL(RGB24ImageChanged(const uint8_t*,QSize)), this, SIGNAL(RGB24ImageChanged(const uint8_t*,QSize)));

    defaultTisCamera();
//    if(m_pTisCamera->isValid()){startTisCamera();}

}
#endif //TIS_CAMERA

#ifdef TIS_CAMERA
void MainWindow::defaultTisCamera()
{
    bool ret;
    QString path = configFilePath();
    QString cameraStateFile = path + "/Camera.xml";
    if( !m_pTisCamera->loadDeviceStateFromFile( cameraStateFile.toStdString() ))
    {
       TisCameraInfo dc = TisCameraInfo::defaultCamera();
        m_pTisCamera->openDevice(dc);
    }
    ret = m_pTisCamera->isValid();
    if(ret)
    {
        //qDebug() << m_pTisCamera->listVideoFormats();
        m_pTisCamera->setVideoFormat("RGB24 (2048x1536)");
        m_pTisCamera->setFrameRate(20);
        m_pTisCamera->initFrameHandlerSink();
        m_pTisCamera->initVCDPropertyAccess();
        m_toolbarCamera->defaultCameraOpened();
        qInfo() << "defaultTisCameraOpened()";
    }
    else
    {
        m_toolbarCamera->defaultCameraFailed();
        qDebug() << "defaultTisCameraFailed()";
        QMessageBox::information(this, QStringLiteral("Error"), QStringLiteral("CameraFailed!") );
    }
}
#endif //TIS_CAMERA

#ifdef TIS_CAMERA
void MainWindow::adjustTisCamera()
{
    qDebug() << "m_tisCamera->showVCDPropertyPage()";
    m_pTisCamera->showVCDPropertyPage();
}
#endif //TIS_CAMERA

#ifdef TIS_CAMERA
void MainWindow::startTisCamera()
{
    QString path = configFilePath();
    QString cameraStateFile = path + "/Camera.xml";
    if( !m_pTisCamera->loadDeviceStateFromFile( cameraStateFile.toStdString() ))
    {
       TisCameraInfo dc = TisCameraInfo::defaultCamera();
        m_pTisCamera->openDevice(dc);
    }
    if(m_pTisCamera->isValid())
    {
        m_pTisCamera->setVideoFormat("RGB24 (2048x1536)");
        m_pTisCamera->setFrameRate(20);
        m_pTisCamera->initFrameHandlerSink();
        m_pTisCamera->initVCDPropertyAccess();
    }
    m_pTisCamera->startLive(false);
}
#endif //TIS_CAMERA


#ifdef TIS_CAMERA
void MainWindow::suspendTisCamera()
{
    m_pTisCamera->suspendLive();
}
#endif //TIS_CAMERA

#ifdef TIS_CAMERA
void MainWindow::closeTisCamera()
{
    m_pTisCamera->closeDevice();
}
#endif //TIS_CAMERA

#ifdef TIS_CAMERA
void MainWindow::selectTisCamera()
{
    bool ret;
    qDebug() << "MainWindow::selectTisCamera()";
    m_pTisCamera->selectDevice();
    ret = m_pTisCamera->isValid();
    if(ret)
    {
        m_pTisCamera->initFrameHandlerSink();
        m_pTisCamera->initVCDPropertyAccess();
        m_toolbarCamera->selectCameraSuccessed();
        qDebug() << "m_toolbarCamera->selectTisCameraSuccessed()";
    }
    else
    {
        m_toolbarCamera->selectCameraFailed();
        qDebug() << "m_toolbarCamera->selectTisCameraFailed()";
    }

}
#endif TIS_CAMERA



void MainWindow::loadImage()
{
    QString fileName = QFileDialog::getOpenFileName(this,
         QStringLiteral("Open Image"), ".\\", QStringLiteral("Image Files (*.png *.jpg *.bmp)"));
    if( !fileName.isEmpty () )
    {
        m_cameraImage->loadImage(fileName);
    }
}

void MainWindow::clearAllMark()
{
    m_centerWidget->clearAll();
}


void MainWindow::saveImageWithMark()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                               "",
                               QStringLiteral("Images (*.jpg *.png *.bmp)"));
    if( !fileName.isEmpty () )
    {
        m_centerWidget->saveImage(fileName, 1);
    }

//    double x_mm, y_mm;
//    int row, col;
//    x_mm = m_encodePos_mm[0];
//    y_mm = m_encodePos_mm[1];
//    qDebug() << "x = " << x_mm << ", y = " << y_mm;
//    m_nozzleDockWidget->getColRow(x_mm, y_mm, row, col);
//    qDebug() << "row = " << row << ", col = " << col;
//    QImage image = m_centerWidget->getImage(true);

//    QString name = m_fileNameDialog->getFileName(row, col);
//    QString dir = m_fileNameDialog->getDir();
//    dir += "\\";
//    dir += name;
//    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
//                               dir,
//                               QStringLiteral("Images (*.jpg *.png *.bmp)"));
//    if( !fileName.isEmpty () )
//    {
//        m_centerWidget->saveImage(fileName, 1);
//        if(row != -1 && m_tableDisplay)
//        {
//            m_tableDisplay->setImage(image, row, col);
//        }
//    }
}

void MainWindow::saveImageWithoutMark()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                               "",
                               QStringLiteral("Images (*.jpg *.png *.bmp)"));
    if( !fileName.isEmpty () )
    {
        m_centerWidget->saveImage(fileName, 0);
    }

//    double x_mm, y_mm;
//    int row, col;
//    x_mm = m_encodePos_mm[0];
//    y_mm = m_encodePos_mm[1];
//    m_nozzleDockWidget->getColRow(x_mm, y_mm, row, col);
//    QImage image = m_centerWidget->getImage(false);

//    QString name = m_fileNameDialog->getFileName(row, col);
//    QString dir = m_fileNameDialog->getDir();
//    dir += "\\";
//    dir += name;
//    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
//                               dir,
//                               QStringLiteral("Images (*.jpg *.png *.bmp)"));
//    if( !fileName.isEmpty () )
//    {
//        m_centerWidget->saveImage(fileName, 0);
//        if(row != -1 && m_tableDisplay)
//        {
//            m_tableDisplay->setImage(image, row, col);
//        }
//    }
}


MainWindow::~MainWindow()
{

#ifdef TIS_CAMERA
    if(m_pTisCamera)
    {
        QString path = configFilePath();
        QString cameraStateFile = path + "/Camera.xml";
        //m_pTisCamera->saveDeviceStateToFile( cameraStateFile.toStdString() );
    }
#endif //TIS_CAMERA

    delete ui;

}

void MainWindow::closeEvent(QCloseEvent *event)
{

    QMainWindow::closeEvent(event);
    QString path = configFilePath();
    QSettings settings( path + "/JHPhoto.ini", QSettings::IniFormat, this );
    QRect rect = geometry();
    settings.setValue("Windows/MainWindow", rect);

    m_toolbarCamera->writeSettings(settings);
    m_pStageControl->writeSettings(settings);

}





